﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading.Tasks;

namespace InstitutionAssitant
{
    public class FileSystemObject
    {
        
        public static void Create(string file, FsoMethod method)
        {
            try
            {
                if (method == FsoMethod.File)
                {
                    WriteFile(file, "");
                }
                else if (method == FsoMethod.Folder)
                {
                    Directory.CreateDirectory(file);
                }
            }
            catch
            {
                throw new UnauthorizedAccessException("无法创建文件");
            }
        }
        public static string WriteFile(string file, string fileContent)
        {
            string str;
            FileInfo info = new FileInfo(file);
            if (!Directory.Exists(info.DirectoryName))
            {
                Directory.CreateDirectory(info.DirectoryName);
            }
            FileStream stream = new FileStream(file, FileMode.Create, FileAccess.Write);
            StreamWriter writer = new StreamWriter(stream, Encoding.UTF8);
            try
            {
                writer.Write(fileContent);
                str = fileContent;
            }
            catch (Exception exception)
            {
                throw new FileNotFoundException(exception.ToString());
            }
            finally
            {
                writer.Flush();
                stream.Flush();
                writer.Close();
                stream.Close();
            }
            return str;
        }
        /// <summary>
        /// 向文件写入内容并根据bool append参数决定是改写还是追加 append=false则改写
        /// </summary>
        public static void WriteFile(string file, string fileContent, bool append)
        {
            FileInfo info = new FileInfo(file);
            if (!Directory.Exists(info.DirectoryName))
            {
                Directory.CreateDirectory(info.DirectoryName);
            }
            StreamWriter writer = new StreamWriter(file, append, Encoding.GetEncoding("utf-8"));
            try
            {
                try
                {
                    writer.Write(fileContent);
                }
                catch (Exception exception)
                {
                    throw new FileNotFoundException(exception.ToString());
                }
            }
            finally
            {
                writer.Flush();
                writer.Close();
            }
        }
    }
    
    public enum FsoMethod
    {
        Folder,
        File,
        All
    }
}
